package sis.report;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static sis.report.RosterReporter.ROSTER_REPORT_FOOTER;
import static sis.report.RosterReporter.ROSTER_REPORT_HEADER;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import org.junit.Before;
import org.junit.Test;

import sis.studentinfo.Course;
import sis.studentinfo.CourseSession;
import sis.studentinfo.Session;
import sis.studentinfo.Student;
import sis.util.DateUtil;


public class RosterReporterTest {
	
	private Session session;
	private final String filename = "testFiledReport.txt";
	@Before
	public void init() {
		session = CourseSession.create(new Course("ENGL", "101"), DateUtil.createDate(2003, 1, 6));
		session.enrool(new Student("A"));
		session.enrool(new Student("B"));
	}
	
	@Test
	public void testRosterReport() throws IOException {
		Writer writer = new StringWriter();
		new RosterReporter(session).writeReport(writer);
		assertReportContents(writer.toString());
	}

	private void assertReportContents(String string) {
		assertEquals(
			String.format(ROSTER_REPORT_HEADER + "A%nB%n" + ROSTER_REPORT_FOOTER, 2), string);
	}
	
	@Test
	public void testFileReport() throws IOException {
		try {
			delete(filename);
			
			new RosterReporter(session).writeReport(filename);
			
			StringBuilder builder = new StringBuilder();
			String line;
			
			BufferedReader reader = new BufferedReader(new FileReader(filename));
			while((line = reader.readLine()) != null ) {
				builder.append(String.format(line + "%n"));
			}
			reader.close();
			assertReportContents(builder.toString());
		} finally {
			delete(filename);
		}
	}

	private void delete(String filename) {
		File file = new File(filename);
		if(file.exists()) {
			assertTrue("unable to delete " + filename, file.delete());
		}
	}
	
}
